package com.info.zhiduoduo.core.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.project.LongTermProjectState;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.core.service.CoreLongTermProjectService;
import com.info.zhiduoduo.repository.entity.company.LongTermProject;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.company.LongTermProjectMapper;

import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CoreLongTermProjectServiceImpl implements CoreLongTermProjectService {

	@Resource
	LongTermProjectMapper longTermProjectMapper;
	@Resource
	CompanyProjectMapper companyProjectMapper;

	@Override
	public void checkLongTermProjectValid() {
		new LongTermProject().selectList(Condition.create().eq("state", LongTermProjectState.SUBMITTED)).forEach(this::checkValid);
	}

	@Override
	public boolean checkValid(int projectid) {
		return checkValid(new LongTermProject().selectById(projectid));
	}

	@Override
	public boolean checkValid(LongTermProject project) {
		Asserts.notNull(project, StatusMsg.StatusMsg_347);

		if (NumberUtil.intIn(project.getState(), LongTermProjectState.CREATED, LongTermProjectState.FINISHED,
				LongTermProjectState.CANCELLED, LongTermProjectState.WASTED)) {
			return false;
		} else if (NumberUtil.equals(project.getState(), LongTermProjectState.SUBMITTED)) {
			Date expireDate = project.getExpireDate();
			if (DateUtil.nowDate().after(expireDate)) {
				// 已过期, 更新
				project.setState(LongTermProjectState.FINISHED).updateById();
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	@Override
	public void checkTotalAmount(LongTermProject project, BigDecimal amount) {
		Asserts.notNull(project, StatusMsg.StatusMsg_347);
		BigDecimal projectamount = project.getProjectamount();
		BigDecimal submittedTotalAmount = companyProjectMapper.sumLongTermProjectSubmittedAmount(project.getProjectid());
		if (projectamount.compareTo(submittedTotalAmount.add(amount)) < 0) {
			// 已经超过总金额
			throw SmartException.of(StatusMsg.StatusMsg_350).setData(submittedTotalAmount);
		}
	}
}
